package com.cskaoyan.service.promotionService;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.promotionVO.couponVO.CouponListVO;
import com.cskaoyan.bean.promotionVO.coupon_userVO.CouponUserVO;
import com.cskaoyan.bean.wx_couponVO.DataBean;
import com.cskaoyan.bean.wx_couponVO.WxCouponListVO;
import com.cskaoyan.bean.wx_couponVO.WxSelectListVO;
import com.cskaoyan.bean.wx_couponVO.WxUserCouponsVO;
import com.cskaoyan.mapper.CouponMapper;
import com.cskaoyan.mapper.CouponUserMapper;
import com.cskaoyan.util.RedeemCodeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.System;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    CouponMapper couponMapper;


    @Override
    public CouponListVO couponList(Integer page, Integer limit, String sort, String order, String name, Short type, Short status) {
        PageHelper.startPage(page, limit);

        CouponExample couponExample = new CouponExample();
        couponExample.setOrderByClause(sort + " " + order);
        CouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andIdIsNotNull().andDeletedEqualTo(false);
        if (type != null) {
            criteria.andTypeEqualTo(type);
        }
        if (status != null) {
            criteria.andStatusEqualTo(status);
        }
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        List<Coupon> couponList = couponMapper.selectByExample(couponExample);

        //更新优惠券的状态
        List<Coupon> newCouponList = getNewCoupons(couponExample, couponList);

        PageInfo<Coupon> couponPageInfo = new PageInfo<>(couponList);
        long total = couponPageInfo.getTotal();
        CouponListVO couponListVO = new CouponListVO();
        couponListVO.setItems(newCouponList);
        couponListVO.setTotal(total);
        return couponListVO;
    }

    private List<Coupon> getNewCoupons(CouponExample couponExample, List<Coupon> couponList) {
        for (Coupon coupon : couponList) {
            if (coupon.getDays() == null) {
                Timestamp endTime = coupon.getEndTime();
                Boolean flag = endTime.before(new Timestamp(System.currentTimeMillis()));

                if (flag) {
                    coupon.setStatus((short) 1);
                    couponMapper.updateByPrimaryKey(coupon);
                }
            }
        }

        return couponMapper.selectByExample(couponExample);
    }

    @Override
    public Coupon couponAdd(Coupon coupon) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        coupon.setAddTime(timestamp);
        coupon.setUpdateTime(timestamp);
        //判断优惠券赠送类型，如果为优惠券码类型，则随机生成优惠券码
        if (coupon.getType() == 2) {
            String bigSmallLetterStrOrNumberRadom = RedeemCodeUtils.createBigSmallLetterStrOrNumberRadom(8);
            coupon.setCode(bigSmallLetterStrOrNumberRadom);
        }

        int code = couponMapper.insertSelective(coupon);

        coupon = couponMapper.selectByPrimaryKey(coupon.getId());
        return coupon;
    }

    @Override
    public int couponDel(Coupon coupon) {
        coupon.setDeleted(true);
        int code = couponMapper.updateByPrimaryKey(coupon);
        return code;
    }

    @Override
    public Coupon couponUpdate(Coupon coupon) {
        coupon.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        if (coupon.getType() == 2) {
            String bigSmallLetterStrOrNumberRadom = RedeemCodeUtils.createBigSmallLetterStrOrNumberRadom(8);
            coupon.setCode(bigSmallLetterStrOrNumberRadom);
        }
        couponMapper.updateByPrimaryKey(coupon);
        Coupon couponVO = couponMapper.selectByPrimaryKey(coupon.getId());
        return couponVO;
    }

    @Override
    public Coupon couponRead(Integer id) {
        Coupon coupon = couponMapper.selectByPrimaryKey(id);
        return coupon;
    }


    @Autowired
    CouponUserMapper couponUserMapper;

    @Override
    public CouponUserVO couponListUser(Integer page, Integer limit, String sort, String order, Integer couponId, Integer userId, Short status) {
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();

        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }

        if (status != null) {
            criteria.andStatusEqualTo(status);
        }
        criteria.andCouponIdEqualTo(couponId).andDeletedEqualTo(false);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        couponUserExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page, limit);
        PageInfo<CouponUser> couponUserPageInfo = new PageInfo<>(couponUsers);
        long total = couponUserPageInfo.getTotal();
        CouponUserVO couponUserVO = new CouponUserVO();
        couponUserVO.setItems(couponUsers);
        couponUserVO.setTotal(total);
        return couponUserVO;
    }

    //实现前台的优惠券显示
    @Override
    public WxCouponListVO wxCouponList(Integer page, Integer size) {

        //更新优惠券的状态
        updateCouponStatus();

        PageHelper.startPage(page, size);
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andIdIsNotNull().andStatusEqualTo((short) 0).andTypeEqualTo((short) 0);
        List<Coupon> couponList = couponMapper.selectByExample(couponExample);

        PageInfo<Coupon> couponPageInfo = new PageInfo<>(couponList);
        long total = couponPageInfo.getTotal();
        WxCouponListVO wxCouponListVO = new WxCouponListVO();
        wxCouponListVO.setCount(total);
        wxCouponListVO.setData(couponList);
        return wxCouponListVO;
    }

    private void updateCouponStatus() {
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andIdIsNotNull();
        List<Coupon> couponList = couponMapper.selectByExample(couponExample);
        for (Coupon coupon : couponList) {
            if (coupon.getTimeType() == 1) {
                Timestamp endTime = coupon.getEndTime();
                Boolean flag = endTime.before(new Timestamp(System.currentTimeMillis()));

                if (flag) {
                    coupon.setStatus((short) 1);
                    couponMapper.updateByPrimaryKey(coupon);
                }
            }
        }
    }


    //显示前台用户的优惠券
    @Override
    public WxUserCouponsVO myCouponList(Integer page, Integer size, Short status, Integer userId) {


        //通过用户 id和优惠券状态关联用户优惠券表，从而关联到优惠券表

        //更新用户的优惠券状态
        updateCouponUserStatus(userId);

        PageHelper.startPage(page, size);
        //获得用户拥有的优惠券
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andStatusEqualTo(status);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        //通过用户优惠券表关联度优惠券表
        List<DataBean> dataBeans = new ArrayList<>();
        for (CouponUser couponUser : couponUsers) {

            DataBean dataBean = new DataBean();
            Integer couponId = couponUser.getCouponId();
            //获得相关的优惠券
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);

            dataBean.setDesc(coupon.getDesc());
            BigDecimal discount = coupon.getDiscount();

            dataBean.setDiscount(discount.toString());
            Timestamp endTime = couponUser.getEndTime();
            Timestamp startTime = couponUser.getStartTime();
            String end = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(endTime);
            String start = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(startTime);
            dataBean.setEndTime(end);
            dataBean.setStartTime(start);

            dataBean.setId(couponUser.getId());
            BigDecimal min = coupon.getMin();
            dataBean.setMin(min.toString());
            dataBean.setName(coupon.getName());
            dataBean.setTag(coupon.getTag());

            dataBeans.add(dataBean);
        }

        WxUserCouponsVO userCouponsVO = new WxUserCouponsVO();
        PageInfo<CouponUser> pageInfo = new PageInfo<>(couponUsers);
        long total = pageInfo.getTotal();
        userCouponsVO.setCount(total);
        userCouponsVO.setData(dataBeans);
        return userCouponsVO;
//        return getWxUserCouponsVO(status, userId);
    }

    private void updateCouponUserStatus(Integer userId) {
        CouponUserExample example = new CouponUserExample();
        CouponUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(example);
        for (CouponUser couponUser : couponUsers) {

            Timestamp endTime = couponUser.getEndTime();
            Boolean flag = endTime.before(new Timestamp(System.currentTimeMillis()));
            if (flag) {
                couponUser.setStatus((short) 1);
                couponUserMapper.updateByPrimaryKey(couponUser);
            }
        }
    }

    private WxUserCouponsVO getWxUserCouponsVO(Short status, Integer userId) {

        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andStatusEqualTo(status);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);


        DataBean dataBean = new DataBean();

        //通过用户优惠券表关联度优惠券表
        List<DataBean> dataBeans = new ArrayList<>();
        for (CouponUser couponUser : couponUsers) {

            Integer couponId = couponUser.getCouponId();
            //获得相关的优惠券
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);

            dataBean.setDesc(coupon.getDesc());
            BigDecimal discount = coupon.getDiscount();

            dataBean.setDiscount(discount.toString());
            Timestamp endTime = couponUser.getEndTime();
            Timestamp startTime = couponUser.getStartTime();
            String end = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(endTime);
            String start = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(startTime);
            dataBean.setEndTime(end);
            dataBean.setStartTime(start);

            dataBean.setId(couponUser.getId());
            BigDecimal min = coupon.getMin();
            dataBean.setMin(min.toString());
            dataBean.setName(coupon.getName());
            dataBean.setTag(coupon.getTag());

            dataBeans.add(dataBean);
        }

        WxUserCouponsVO userCouponsVO = new WxUserCouponsVO();
        PageInfo<CouponUser> pageInfo = new PageInfo<>(couponUsers);
        long total = pageInfo.getTotal();
        userCouponsVO.setCount(total);
        userCouponsVO.setData(dataBeans);
        return userCouponsVO;
    }

    @Override
    public int receiveCoupon(Integer couponId, Integer userId) {

        //更新优惠券的状态
        updateCouponStatus();

        //根据用户id去查询用户优惠券表,获得用户拥有的优惠券
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        //得到要领取的优惠券
        Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
        int code = -1;

        //利用hashmap来存储用户拥有的优惠券,判断该用户是否领取过该优惠券
        HashMap<Integer, Integer> map = new HashMap<>();
        for (CouponUser couponUser : couponUsers) {
            map.put(couponUser.getId(), couponUser.getCouponId());
        }

        //用户已有该优惠券
        if (map.containsValue(couponId)) {
            //判断该优惠券是否限领一张
            if (coupon.getLimit() == 1) {//限领一张
                return 0;

            } else if (coupon.getLimit() == 0) {//可重复领取,判断该优惠券的数量
                if (coupon.getTotal() == 0) {//无限量
                    code = getCode(couponId, userId, coupon);

                } else if (coupon.getTotal() == 1) {//优惠券有数量限制，且只有最后一张

                    code = getCode(couponId, userId, coupon);//用户领取最后一张，该优惠券数量减一，该优惠券下架
                    couponMapper.updateTotal(couponId);
                    couponMapper.updateStatus(couponId);

                } else {//优惠券有数量限制，不是最后一张
                    code = getCode(couponId, userId, coupon);//用户领取一张，该优惠券数量减一
                    couponMapper.updateTotal(couponId);
                }
            } else {//优惠券有限制用户领取的优惠券数量

                //先判断该用户领取的该优惠券数量是否到达领取上限
                int couponSum = couponUserMapper.selectCouponCount(couponId);

                if (coupon.getLimit() > couponSum) {//没超过限制

                    if (coupon.getTotal() == 0) {//优惠券的总数无限量
                        code = getCode(couponId, userId, coupon);

                    } else if (coupon.getTotal() == 1) {//优惠券的总数有数量限制，且只有最后一张

                        code = getCode(couponId, userId, coupon);//用户领取最后一张，该优惠券数量减一，该优惠券下架
                        couponMapper.updateTotal(couponId);
                        couponMapper.updateStatus(couponId);

                    } else {//优惠券的总数有数量限制，不是最后一张
                        code = getCode(couponId, userId, coupon);//用户领取一张，该优惠券数量减一
                        couponMapper.updateTotal(couponId);
                    }
                } else {//超过限制
                    return 3;
                }
            }
        } else {//用户没有该优惠券
            code = getCode(couponId, userId, coupon);
        }

        if (code == 1) {
            return 1;
        } else {
            return 2;
        }
    }

    private int getCode(Integer couponId, Integer userId, Coupon coupon) {
        CouponUser couponUser = new CouponUser();
        couponUser.setUserId(userId);
        couponUser.setCouponId(couponId);
        couponUser.setStatus((short) 0);
        //时间单独判断,相对天数or绝对时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        //相对天数
        if (coupon.getTimeType() == 0) {
            couponUser.setStartTime(timestamp);

            //要增加的时间
            Short days = coupon.getDays();
            //使用Calendar类来进行时间的加减运算
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR, days);
            Timestamp timestamp1 = new Timestamp(calendar.getTimeInMillis());
            couponUser.setEndTime(timestamp1);

            couponUser.setAddTime(timestamp);
            couponUser.setUpdateTime(timestamp);

            //绝对天数
        } else {
            couponUser.setStartTime(coupon.getStartTime());
            couponUser.setEndTime(coupon.getEndTime());
            couponUser.setAddTime(timestamp);
            couponUser.setUpdateTime(timestamp);
        }

        couponUser.setDeleted(false);

        return couponUserMapper.insertSelective(couponUser);
    }

    @Override
    public int exchangeCoupon(String code, Integer userId) {

        //更新优惠券的状态
        updateCouponStatus();

        //根据兑换码获得相关的优惠券，同时判断该优惠券是否过期
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andCodeEqualTo(code);


        List<Coupon> coupons = couponMapper.selectByExample(couponExample);

        Coupon coupon = coupons.get(0);
        Short status = coupon.getStatus();
        if (status == 1) {
            return 4;
        } else if (status == 2) {
            return 5;
        }

        //该优惠券可以正常兑换,复用上面的receiveCoupon方法
        int receiveCoupon = receiveCoupon(coupon.getId(), userId);
        return receiveCoupon;
    }

    @Override
    public List<DataBean> selectlistCoupon(Integer id) {

        //通过用户 id和优惠券状态关联用户优惠券表，从而关联到优惠券表
        //更新用户优惠券表的状态
        updateCouponUserStatus(id);

        //获得用户拥有的优惠券
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andUserIdEqualTo(id).andStatusEqualTo((short) 0);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);


        //通过用户优惠券表关联度优惠券表
        List<DataBean> dataBeans = new ArrayList<>();
        for (CouponUser couponUser : couponUsers) {
            DataBean dataBean = new DataBean();
            Integer couponId = couponUser.getCouponId();
            //获得相关的优惠券
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
            dataBean.setDesc(coupon.getDesc());
            BigDecimal discount = coupon.getDiscount();

            dataBean.setDiscount(discount.toString());
            Timestamp endTime = couponUser.getEndTime();
            Timestamp startTime = couponUser.getStartTime();
            String end = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(endTime);
            String start = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(startTime);
            dataBean.setEndTime(end);
            dataBean.setStartTime(start);

            dataBean.setId(coupon.getId());
            BigDecimal min = coupon.getMin();
            dataBean.setMin(min.toString());
            dataBean.setName(coupon.getName());
            dataBean.setTag(coupon.getTag());

            dataBeans.add(dataBean);
        }
        return dataBeans;
    }
}
